package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.spzx.manager.helper.MenuHelper;
import com.atguigu.spzx.manager.mapper.SysMenuMapper;
import com.atguigu.spzx.manager.service.SysMenuService;
import com.atguigu.spzx.model.entity.system.SysMenu;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.service.exception.GuiguException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * @author MikeCoder
 * @create 2023-12-0615:51
 * @description:
 * @verson:
 */
@Service
@Transactional
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    @Transactional(readOnly = true)
    public List<SysMenu> findMenuTree() {
        //1.查找所有的菜单
        List<SysMenu> menuList = sysMenuMapper.selectAllMenu();
        //2.判断菜单集合是否为空
        if (CollectionUtil.isEmpty(menuList)) {
            return null;
        }

        //菜单集合不为空，就生成菜单树
        List<SysMenu> menusTree = MenuHelper.buildTree(menuList);

        return menusTree;
    }

    @Override
    public void addMenu(SysMenu sysMenu) {
        sysMenuMapper.insert(sysMenu);
    }

    @Override
    public void addChildrenMenu(SysMenu sysMenu) {
        sysMenuMapper.insertChildren(sysMenu);
    }

    @Override
    public String getParentTitle(Long id) {
        String ParentTitle = sysMenuMapper.selectParentMenu(id).getTitle();
        return ParentTitle;
    }

    @Override
    public void updateMenu(SysMenu sysMenu, String parentTitle) {
        if(parentTitle != null && !parentTitle.equals("无")){
            SysMenu parentMenu = sysMenuMapper.selectParentMenu(parentTitle);
            Long id = parentMenu.getId();
            sysMenu.setParentId(id);
        }
        sysMenuMapper.update(sysMenu);
    }

    @Override
    public void removeSysMenu(SysMenu sysMenu) {
        //删除本菜单
        sysMenuMapper.delete(sysMenu.getId());
        //删除子菜单
        List<SysMenu> children = sysMenu.getChildren();
        for (SysMenu child : children) {
            sysMenuMapper.delete(child.getId());
        }
    }
}
